package user;

import entity.ExCourse;
import entity.ExCoursesContainer;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.namespace.QName;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.ws.Service;
import org.xml.sax.SAXException;

@XmlSeeAlso(ExCoursesContainer.class)
public class User {

    private Marshaller marshaller;
    private static Unmarshaller unmarshaller;
    private static JAXBContext jaxbContext;
    private static SchemaFactory schemaFactory;
    private static List<ExCourse> list;
    private static ExCoursesContainer container;
    private static File file;

    public static void main(String[] args) throws MalformedURLException, FileNotFoundException {


//WebService connection
        final URL url = new URL("http://127.0.0.1:9000/simple");
        final QName serviceName = new QName("http://webservice/", "SimpleServiceImplService");
        final QName portName = new QName("http://webservice/", "SimpleServiceImplPort");

        final Service service = Service.create(url, serviceName);
        final SimpleService xmlService = service.getPort(portName, SimpleService.class);


//File unmarshalling
        file = new File("course.xml");
        try {
            jaxbContext = JAXBContext.newInstance(User.class);
            unmarshaller = jaxbContext.createUnmarshaller();

            schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = schemaFactory.newSchema(new File("schema.xsd"));
            unmarshaller.setSchema(schema);

        } catch (JAXBException e) {
            System.out.println("Jaxb exception: " + e.getMessage());
        } catch (SAXException e) {
            System.out.println("SAX exception: " + e.getMessage());
        }

        try {
            container = (ExCoursesContainer) unmarshaller.unmarshal(file);
        } catch (JAXBException e) {
            System.out.println(e.getMessage());
        }

        System.out.println("Sending container...");
        List<ExCourse> coursesList = container.getList();
        for (ExCourse exCourse : coursesList) {
            System.out.println(exCourse);
        }


        xmlService.processXml(container);

    }
}
